﻿using HotelManagementClient.Utlis;
using HotelManagementClient.View.ViewModel;
using HotelManagementClient.ViewModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using NativeWifi;
using Color = System.Windows.Media.Color;
using ColorConverter = System.Windows.Media.ColorConverter;
using HotelManagementClient.Model;
using MQTTnet.Protocol;
using MQTTnet;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections.Specialized;
using System.Windows.Media;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using UnityEngine;
using Microsoft.Win32;
using System;
using HotelManagementClient.View;
using System.IO.Ports;



namespace HotelManagementClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window          
    {
        //聊天的用户名
        public static string login_username;//登录人用户名
        public static string login_avatar;//登录人头像
        public static string login_nickname;//登录人昵称

        public static string msg_username;//消息接收人
        public static int msg_user_type;//消息接收人类型

        public static string des3Key = "Tt3rLPrDIVIhXqAz";// 长度控制为16，作为3DES加密用的key

        
        public static string login_token;//登录人token
        public static int login_hotel_id;//默认酒店编号
        public static string login_hotel_name;//默认酒店名称
        public static int login_user_type;//用户类型
        public static int COUNT=0;//发送次数
        public static string msg_group_code;//聊天的群组编号


        MqttClient mqttClient = new MqttClient();


        //群聊天记录
        public List<ChatGroupContent> chatGroupContents = new List<ChatGroupContent>();

        /// <summary>
        /// 主窗体
        /// </summary>
        public MainWindow()
        {


            //定时任务创建
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 2);//设置的间隔为2秒
            timer.Tick += timer_Tick;
            timer.IsEnabled = true;
            timer.Start();



            InitializeComponent();

            GetWlanStatus();//查询网络

            GetWlanStatus();//查询网络
            SqlLiteUtil.InitSqlite();//初始化数据库
            SqlLiteUtil.CreateChatUser();//创建用户表
            SqlLiteUtil.CreateChatContent();//创建个人聊天内容表
            SqlLiteUtil.CreateChatGroup();//创建群组表
            SqlLiteUtil.CreateChatGroupUser();//创建群组用户表
            SqlLiteUtil.CreateChatGroupContent();//创建群组聊天内容表
            SqlLiteUtil.UpdateDatabase(); //数据库更新

            
            //连接mqtt
            if(!string.IsNullOrEmpty(login_token))
            {
                //主题
                var topicList = new List<string> { "ygs/chat/business/" + login_hotel_id };
                string clientId = "user_" + login_token;
                mqttClient.MqttClientCon(topicList, clientId);
                mqttClient.OnMessage += OnMessgae;
            }
            


            if (mqttClient !=null && mqttClient.m_MqttClient !=null &&  mqttClient.m_MqttClient.IsConnected)
            {
                GetChatGroup();
                GetChatUser(0);
            }
        }

        /// <summary>
        /// 自动加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //系统启动离线卡状态异常
            AppConfigUtil.SetValue("SerialPort", "status", "0");

            //获取登录配置信息
            login_hotel_id = Convert.ToInt32(Encryptor.DecryptData(AppConfigUtil.GetValue("LoginUser", "hotelId"), des3Key));
            login_token = Encryptor.DecryptData(AppConfigUtil.GetValue("LoginUser", "accessToken"), des3Key);
            login_user_type = Convert.ToInt32(Encryptor.DecryptData(AppConfigUtil.GetValue("LoginUser", "userType"), des3Key));
            login_hotel_name = Encryptor.DecryptData(AppConfigUtil.GetValue("HotelInfo", "hotelName"), des3Key);

            login_username = Encryptor.DecryptData(AppConfigUtil.GetValue("LoginUser", "loginUserName"), des3Key);
            login_avatar = StrUtils.baseUrl+Encryptor.DecryptData(AppConfigUtil.GetValue("LoginUser", "loginAvatar"), des3Key);
            
            string loginRealName = Encryptor.DecryptData(AppConfigUtil.GetValue("LoginUser", "loginRealName"), des3Key);
            if (string.IsNullOrEmpty(loginRealName))
            {
                login_nickname = Encryptor.DecryptData(AppConfigUtil.GetValue("LoginUser", "loginNickName"), des3Key);
            }
            else
            {
                login_nickname = loginRealName;
            }

            //赋值到界面
            Dispatcher.Invoke(
                new Action(() =>
                {
                    //设置登录人名称
                    LoginUser.Content = "(" + login_nickname + ")";
                    HotelName.Content = login_hotel_name;
                    COUNT++;
                }
            ));

            try
            {
                //每次都清空WrapPanel：环绕面板的内容 
                CustomerClassification.Children.Clear();

                List<CustomerClassification> list = new List<CustomerClassification>() {
                    new CustomerClassification(4, "意向客户"),
                    new CustomerClassification(1, "预定客户"),
                    new CustomerClassification(2, "在住客户"),
                    new CustomerClassification(3, "离店客户"),
                    new CustomerClassification(5, "商城会员"),
                    new CustomerClassification(6, "协议单位"),
                    new CustomerClassification(7, "门店职员"),
                    new CustomerClassification(8, "平台客服")
                };

                foreach (var item in list)
                {
                    Button button = new Button();
                    button.Content = item.Name;

                    BrushConverter conv = new BrushConverter();
                    Brush bru = conv.ConvertFromInvariantString("#ffffff") as Brush;
                    button.Background = (System.Windows.Media.Brush)bru;

                    switch (item.ClassId)
                    {
                        case 1:
                            button.Click += new RoutedEventHandler(Booking_Customers_Click);
                            break;
                        case 2:
                            button.Click += new RoutedEventHandler(Resident_Customers_Click);
                            break;
                        case 3:
                            button.Click += new RoutedEventHandler(Outbound_Customers_Click);
                            break;
                        case 4:
                            button.Click += new RoutedEventHandler(Intended_Customers_Click);
                            break;
                        case 5:
                            button.Click += new RoutedEventHandler(Mall_Members_Click);
                            break;
                        case 6:
                            button.Click += new RoutedEventHandler(Agreement_Unit_Click);
                            break;
                        case 7:
                            button.Click += new RoutedEventHandler(Store_Staff_Click);
                            break;
                        case 8:
                            button.Click += new RoutedEventHandler(Customer_Service_Click);
                            break;
                    }
                    CustomerClassification.Children.Add(button);
                }

                GetWlanStatus();
            }
            catch
            {
                MessageBox.Show("计算机网络连接失败!");
            }
        }


        /// <summary>
        /// 发送聊天数据
        /// </summary>
        /// <param name="chatMsg"></param>
        public void SendChatMsg(string chatMsg)
        {
            //加密
            string encryptorMsg=Encryptor.EncryptData(chatMsg, des3Key);
            byte[] msggbu = Encoding.UTF8.GetBytes(encryptorMsg);
            MqttApplicationMessage applicationMessage = new();
            CancellationToken cancellationToken1 = new CancellationToken();
            applicationMessage.Topic = "ygs/chat/subscribe/"+login_hotel_id ;
            applicationMessage.Payload = msggbu;
            applicationMessage.QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
            applicationMessage.Retain = false;
            mqttClient.Send(applicationMessage, cancellationToken1);
        }

        /// <summary>
        /// 断开mqtt连接
        /// </summary>
        private void MqttClose()
        {
            mqttClient.Dispose();
        }

        /// <summary>
        /// 消息监控
        /// </summary>
        /// <param name="msg"></param>
        private void OnMessgae(string msg)
        {
          
            string encryptorMsg=Encryptor.DecryptData(msg, des3Key);
            if (string.IsNullOrEmpty(encryptorMsg) )
            {
                //错误的数据
                WriteLog.Write(1, encryptorMsg);
                return;
            }
            //正确数据
            WriteLog.Write(0, encryptorMsg);

            JObject obj=StrUtils.JosnToOjbect(encryptorMsg);

            if(obj.Property("type") == null)
            {
                //无效的数据
                return;
            }
            int type = Convert.ToInt16(obj["type"]);//消息类型
            switch (type)
            {
                //登录人信息
                case 0://登录人个人信息 {type:0,"nickName":"","avatar":""，"accessToken":""}
                    if (obj["accessToken"].ToString().Equals(login_token))
                    {
                        login_nickname = obj["nickName"].ToString();
                        login_avatar = obj["avatar"].ToString();
                        login_username = obj["userName"].ToString();

                        AppConfigUtil.SetValue("LoginUser", "loginUserName", Encryptor.EncryptData(login_username, des3Key));
                        AppConfigUtil.SetValue("LoginUser", "loginNickName", Encryptor.EncryptData(login_nickname, des3Key));
                        AppConfigUtil.SetValue("LoginUser", "loginAvatar", Encryptor.EncryptData(login_avatar, des3Key));
                        AppConfigUtil.SetValue("LoginUser", "loginRealName", "");


                        login_hotel_name = obj["hotelName"].ToString();
                        Dispatcher.Invoke(
                            new Action(() =>
                            {
                                //设置登录人名称
                                LoginUser.Content = "(" + login_nickname + ")";
                                HotelName.Content = login_hotel_name;
                                COUNT++;
                            }
                        ));
                    }
                    break;
                //接收个人消息
                case 1://个人消息 {"msg":"123123""avatar":"http:","type":1,"userName":"T2281721310"}
                    //接收者
                    string recipientUser = obj["recipientUser"].ToString();
                    //发送者
                    string sendUser = obj["sendUser"].ToString();
                    //是我的消息
                    if (!string.IsNullOrEmpty(login_username) && recipientUser.Equals(login_username))
                    {

                        //获取发送者用户信息
                        ChatUser sendChatUser = SqlLiteUtil.QueryOneChatUser(msg_user_type, sendUser);
                        if (null == sendChatUser)
                        {
                            Console.WriteLine("未获取到发送者信息");
                            return;
                        }
                        //播放消息声音
                        Dispatcher.BeginInvoke(new Action(delegate
                        {
                            MediaPlayer player = new MediaPlayer();
                            Uri uri = new Uri(AppDomain.CurrentDomain.BaseDirectory + "media\\chatmedia.mp3");
                            player.Open(uri);
                            player.Play();
                        }));

                        //消息内容
                        string sendMsg = obj["msg"].ToString();
                        //保存用户的聊天信息
                        SqlLiteUtil.SaveChatContent(sendUser, recipientUser, sendMsg,DateUtil.NowDateZ());
                        //如果打开了窗口就赋值到聊天窗口
                        if (sendUser.Equals(msg_username))
                        {
                            //赋值到聊天框
                            List<ChatMessage> chatContents = new List<ChatMessage>();
                            List<ChatContent> sqlLiteChatContents = SqlLiteUtil.QueryChatContent(sendUser, recipientUser);
                            sqlLiteChatContents.ForEach(chatContent =>
                            {
                                if (chatContent.sendUser.Equals(login_username))
                                {
                                    chatContents.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = "0", MessageLocation = TypeLocalMessageLocation.chatSend, Avatar = login_avatar, NickName = login_nickname, CreateTime = chatContent.createTime });
                                }
                                else
                                {
                                    chatContents.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = "0", MessageLocation = TypeLocalMessageLocation.chatRecv, Avatar = sendChatUser.avatar, NickName = sendChatUser.nickName, CreateTime = chatContent.createTime });
                                }
                            });
                            setChatMessage(chatContents);
                        }
                    }
                    else
                    {
                        Console.Write("非当前用户的个人消息：" + encryptorMsg);
                    }
                    break;
                //接收群发消息
                case 2: //群发消息 {type:2,"groupCode": 1，"sendUser":"11111","msg":"消息"}
                    string groupCode=obj["groupCode"].ToString();//群组编号
                    string groupSendUser = obj["sendUser"].ToString();//发送者
                    //1、判断当前登录用户是否在这个群组中
                    if (!string.IsNullOrEmpty(login_username) && !groupSendUser.Equals(login_username) && SqlLiteUtil.CheckChatGroupUser(login_username, groupCode))
                    {

                        //群组名称
                        string groupNickName = obj["nickName"].ToString();//发送者昵称
                        string groupAvatar = obj["avatar"].ToString();//发送者头像

                        if (!ImgUtil.RemoteFileExists(groupAvatar))
                        {
                            groupAvatar = "https://www.ygs.cc/prod-api/file/statics/weichat/9.jpeg";
                        }

                        string groupCreateTime = obj["createTime"].ToString();//发送时间
                        string groupMsg = obj["msg"].ToString();//消息内容
                        string groupMsgType = Convert.ToString(obj["msgType"]);//消息类型
                        //2、存在则保存聊天信息
                        if (!SqlLiteUtil.CheckChatGroupContent(groupCode, groupSendUser, groupMsg, groupCreateTime))
                        {
                            GetChatGroup();

                            SqlLiteUtil.SaveChatGroupContent(groupCode, groupSendUser, groupNickName, groupAvatar, groupMsg, groupCreateTime, groupMsgType);

                            chatGroupContents.Add(new ChatGroupContent(groupCode, groupSendUser, groupNickName, groupAvatar, groupMsg, groupCreateTime, groupMsgType));

                            chatGroupContents = chatGroupContents.OrderBy(s => s.createTime).ToList();
                            if (groupCode.Equals(msg_group_code))
                            {
                                //赋值到聊天框
                                List<ChatMessage> chatContents = new List<ChatMessage>();

                                chatGroupContents.ForEach(chatContent =>
                                {
                                    if (chatContent.sendUser.Equals(login_username))
                                    {
                                        chatContents.Add(new ChatMessage()
                                        {
                                            Message = chatContent.chatMsg,
                                            MsgType = chatContent.msgType,
                                            MessageLocation = TypeLocalMessageLocation.chatSend,
                                            Avatar = chatContent.avatar,
                                            NickName = chatContent.nickName,
                                            CreateTime = chatContent.createTime
                                        });
                                    }
                                    else
                                    {
                                        chatContents.Add(new ChatMessage()
                                        {
                                            Message = chatContent.chatMsg,
                                            MsgType = chatContent.msgType,
                                            MessageLocation = TypeLocalMessageLocation.chatRecv,
                                            Avatar = chatContent.avatar,
                                            NickName = chatContent.nickName,
                                            CreateTime = chatContent.createTime
                                        });
                                    }

                                });
                                setChatMessage(chatContents);
                            }
                        }
                        Dispatcher.BeginInvoke(new Action(delegate
                        {
                            MediaPlayer player = new MediaPlayer();
                            Uri uri = new Uri(AppDomain.CurrentDomain.BaseDirectory + "media\\chatmedia.mp3");
                            player.Open(uri);
                            player.Play();


                            List<ChatGroup> groups = SqlLiteUtil.QueryChatGroup(login_username, login_hotel_id);
                            groups.ForEach(x =>
                            {
                                if (groupCode.Equals(x.groupCode))
                                {
                                    x.noticeColor = "#c85961";
                                }
                            });
                            ListViewChatGroup.ItemsSource = groups;

                        }));
                    }
                    else
                    {
                        Console.Write("非当前用户的群组消息：" + encryptorMsg);
                    }
                    break;
                //用户列表消息
                case 3://用户列表  {type:3 ,"userType":"0-N","userList":[{"userName":"","nickName":"',"avatar":""}]}
                    int usertype = Convert.ToInt16(obj["userType"]);
                    string username = obj["userName"].ToString();
                    if (!string.IsNullOrEmpty(login_username) && username.Equals(login_username))
                    {
                        string userList = obj["userList"].ToString();
                        List<ChatUser> list = JsonConvert.DeserializeObject<List<ChatUser>>(userList);
                        list.Remove(list.FirstOrDefault(t => t.userName == login_username)); //移除当前登录用户
                        if (list != null)
                        {
                            list.ForEach(c =>
                            {
                                //检查用户信息
                                if (!SqlLiteUtil.CheckChatUser(Convert.ToInt16(c.userType), c.userName, c.avatar))
                                {
                                    //保存用户信息
                                    SqlLiteUtil.SaveChatUser(Convert.ToInt16(c.userType), c.userName, c.nickName, c.avatar);
                                };
                            });
                        }
                    }
                    break;
                //群列表
                case 4://群列表 {type:4,"userName":"登录人","groupList":[{"groupCode":"111aa22","groupName":"群名称"}]}
                    string username4 = obj["userName"].ToString();
                    if (!string.IsNullOrEmpty(login_username) &&login_username.Equals(username4))
                    {
                        int hotelId4 = Convert.ToInt32(obj["hotelId"]);
                        string groupList = obj["groupList"].ToString();
                        List<ChatGroup> list = JsonConvert.DeserializeObject<List<ChatGroup>>(groupList);
                        if (list != null)
                        {
                            list.ForEach(c =>
                            {
                                //检查群信息是否存在 没有则添加
                                if (!SqlLiteUtil.CheckChatGroup(c.groupCode, hotelId4))
                                {
                                    //保存群组信息
                                    SqlLiteUtil.SaveChatGroup(c.groupCode, c.groupName, c.groupAvatar, c.createUser, c.createTime, hotelId4);
                                }

                                //检查用户是否在群中 没有则添加
                                if (!SqlLiteUtil.CheckChatGroupUser(login_username, c.groupCode))
                                {
                                    SqlLiteUtil.SaveChatGroupUser(c.groupCode, login_username, login_nickname, login_avatar);
                                }
                            });
                        }
                    }
                    break;
                //告知客户端群聊不存在了 {type:5, "groupCode":""}
                case 5:
                    string groupcode5 = obj["groupCode"].ToString();
                    if (string.IsNullOrEmpty(groupcode5))
                    {
                        //群组信息空值
                        return;
                    }
                    SqlLiteUtil.DisableGroup(groupcode5);
                    break;
                //获取群用户列表
                case 6:
                    string groupcode = obj["groupCode"].ToString();
                    //获取到群编号并且为当前群组信息
                    if (!string.IsNullOrEmpty(groupcode) && groupcode.Equals(msg_group_code))
                    {
                        //用户列表
                        string groupuserlist = obj["userList"].ToString();
                        //转换成群成员对象
                        List<GroupUserItem> list = JsonConvert.DeserializeObject<List<GroupUserItem>>(groupuserlist);
                        if (list != null)
                        {
                            list.ForEach(gu =>
                            {
                                //检查群里的成员 不存在则添加
                                if (!SqlLiteUtil.CheckChatGroupUser(gu.userName, groupcode))
                                {
                                    SqlLiteUtil.SaveChatGroupUser(groupcode, gu.userName, gu.nickName, gu.avatar);
                                }
                            });
                        }
                    }
                    break;
                //获取用户聊天记录
                case 8:
                    //{type:8,"startTime":"", "promoter":""T1010110","chatContent":[{"userType":"0-N","sendUser":"11111","recipientUser":"22222222","msg":"消息","createTime":""}]}
                    string userPromoter = obj["promoter"].ToString();
                    string userChatContent = obj["chatContent"].ToString();
                    if (!string.IsNullOrEmpty(login_username) && userPromoter.Equals(login_username))
                    {
                        List<ChatContentOffline> list = JsonConvert.DeserializeObject<List<ChatContentOffline>>(userChatContent);
                        list.ForEach(uc =>
                        {
                            string userSendUser = uc.sendUser;
                            string userRecipientUser = uc.recipientUser;
                            string userChatMsg = uc.msg;
                            string userCreateTime = uc.createTime;
                            SqlLiteUtil.SaveChatContent(userSendUser, userRecipientUser, userChatMsg, userCreateTime);
                        });

                    }
                    break;
                //获取群聊天记录
                case 9:
                    //{type:9,"startTime":"","promoter":""T1010110",groupCode":"","chatContent":[{"sendUser":"11111","msg":"消息", "nickName":"", "avatar":"","createTime":""}]}
                    string groupPromoter = obj["promoter"].ToString();
                    if (!string.IsNullOrEmpty(login_username) && groupPromoter.Equals(login_username))//自己的群
                    {
                        string currentGroupCode = obj["groupCode"].ToString();
                        string currentChatContent = obj["chatContent"].ToString();
                        List<ChatGroupContentOffline> list = JsonConvert.DeserializeObject<List<ChatGroupContentOffline>>(currentChatContent);
                        if (list != null)
                        {
                            list.ForEach(oc =>
                            {
                                string groupSendUser = oc.sendUser;
                                string groupMsg = oc.msg;
                                string groupNickName = oc.nickName;
                                string groupAvatar = oc.avatar;
                                string groupCreateTime = oc.createTime;
                                string groupMsgType = oc.msgType;
                                //消息不存  保存聊天信息
                                if (!SqlLiteUtil.CheckChatGroupContent(currentGroupCode, groupSendUser, groupMsg, groupCreateTime))
                                {
                                    SqlLiteUtil.SaveChatGroupContent(currentGroupCode, groupSendUser, groupNickName, groupAvatar, groupMsg, groupCreateTime, groupMsgType);
                                }
                            });
                        }
                    }
                    break;
                //主动组群推送
                case 10:
                    //当前人的物业
                    if (obj["propertyId"] != null && login_hotel_id.Equals(obj["propertyId"].ToString()))
                    {
                        //检查群信息是否存在 
                        string groupCode10 = obj["groupCode"].ToString();
                        int hotelId10 = Convert.ToInt32(obj["hotelId"]);
                        if (!SqlLiteUtil.CheckChatGroup(groupCode10, hotelId10))
                        {
                            string groupName10 = obj["groupName"].ToString();
                            string groupAvatar10 = obj["groupAvatar"].ToString();
                            string createUser10 = obj["createUser"].ToString();
                            string creatTime10 = obj["creatTime"].ToString();

                            //保存群信息
                            SqlLiteUtil.SaveChatGroup(groupCode10, groupName10, groupAvatar10, createUser10, creatTime10, hotelId10);
                            //保存群成员
                            string userList = obj["userList"].ToString();
                            List<GroupUserItem> list = JsonConvert.DeserializeObject<List<GroupUserItem>>(userList);
                            if (null != list)
                            {
                                list.ForEach(gu10 =>
                                {
                                    SqlLiteUtil.SaveChatGroupUser(groupCode10, gu10.userName, gu10.nickName, gu10.avatar);
                                });
                            }
                        }
                    }
                    break;
            }
        }

        /// <summary>
        /// 定时任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer_Tick(object sender, EventArgs e)//计时执行的程序
        {
            GetWlanStatus();
            //登录用户信息上传 
            if (mqttClient != null && mqttClient.m_MqttClient != null && mqttClient.m_MqttClient.IsConnected)
            {
                if (COUNT == 0 && string.IsNullOrEmpty(login_nickname))
                {
                    var postDataUser = new { type = 0, accessToken = login_token, propertyId = login_hotel_id };
                    SendChatMsg(JsonConvert.SerializeObject(postDataUser));
                    //默认点击第一用户列表
                    GetChatUser(0);
                    GetChatGroup();
                }
            }
            else
            {
                //连接mqtt
                if (!string.IsNullOrEmpty(login_token))
                {
                    //主题
                    var topicList = new List<string> { "ygs/chat/business/" + login_hotel_id };
                    string clientId = "user_" + login_token;
                    mqttClient.MqttClientCon(topicList, clientId);
                    mqttClient.OnMessage += OnMessgae;
                }
            }

            //检查通讯状况
            string status = AppConfigUtil.GetValue("SerialPort", "status");
            if ("1".Equals(status))
            {
                SmartCardIssuer.Content = "通讯正常";
                SmartCardIssuer.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#0ee694")); 
            }
            else
            {
                SmartCardIssuer.Content = "通讯异常...";
                SmartCardIssuer.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#bd444d"));
            }

        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="chatUserType">用户分类(0预定用户、1在住用户、2离店客户、3意向客户、4商城会员、5协议单位、6门店职员、7平台客服)</param>
        public void GetChatUser(int chatUserType)
        {
            var postData = new { type = 3, userType = chatUserType, accessToken = login_token, propertyId = login_hotel_id };
            string msg = JsonConvert.SerializeObject(postData);
            SendChatMsg(msg);

            Dispatcher.BeginInvoke(new Action(delegate
            {
                ListViewChatUser.ItemsSource = SqlLiteUtil.QueryChatUser(chatUserType);
            }));
        }

        /// <summary>
        /// 获取群组列表
        /// </summary>
        public void GetChatGroup()
        {
            var postData = new { type = 4, accessToken = login_token, propertyId = login_hotel_id };
            string msg = JsonConvert.SerializeObject(postData);
            SendChatMsg(msg);

            Dispatcher.BeginInvoke(new Action(delegate
            {
                ListViewChatGroup.ItemsSource = SqlLiteUtil.QueryChatGroup(login_username, login_hotel_id);
            }));

        }

        /// <summary>
        /// 获取聊天的用户名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void GetUserName(object sender, MouseButtonEventArgs e)
        {
            StackPanel? s = sender as StackPanel;
            if (s != null)
            {
                ChatGroupUserGrid.Visibility = Visibility.Hidden;

                ChatUser chatuser = s.Tag as ChatUser;
                string username = chatuser.userName;



                if (string.IsNullOrEmpty(username))
                {
                    MessageBox.Show("未选择用户进行聊天");
                    return;
                }
                else
                {
                    //展示聊天内容框
                    ChatGrid.Visibility = Visibility.Visible;
                    ShowGroupUser.Visibility = Visibility.Hidden;
                    Chat_Object.Content = "与 " + chatuser.nickName + " 聊天中";
                    idScrollViewerASC.ScrollToBottom();
                }



                //赋值用户名
                msg_username = username;
                msg_user_type = Convert.ToInt32(chatuser.userType);
                msg_group_code = "";


                //获取与当前用户的最后一条记录信息
                string lastTime = SqlLiteUtil.QueryChatContentByLastTime(login_username, msg_username);
                if (!string.IsNullOrEmpty(lastTime))
                {
                    //获取离线聊天内容
                    var postDataUser = new { type = 8, accessToken = login_token, startTime = lastTime, userName = msg_username, userType = msg_user_type, propertyId = login_hotel_id };
                    //发送聊天数据
                    SendChatMsg(JsonConvert.SerializeObject(postDataUser));
                }

                //赋值到聊天框
                List<ChatMessage> chatMessage = new List<ChatMessage>();

                //获取聊天信息并赋值
                List<ChatContent> sqlLiteChatContents = SqlLiteUtil.QueryChatContent(login_username, username);

                sqlLiteChatContents.ForEach(chatContent =>
                {
                    if (chatContent.sendUser.Equals(username))
                    {
                        //获取用户
                        chatMessage.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = chatContent.chatMsgType, MessageLocation = TypeLocalMessageLocation.chatRecv, Avatar = chatuser.avatar, NickName = chatuser.nickName, CreateTime = chatContent.createTime });
                    }
                    else
                    {
                        chatMessage.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = chatContent.chatMsgType, MessageLocation = TypeLocalMessageLocation.chatSend, Avatar = login_avatar, NickName = login_nickname, CreateTime = chatContent.createTime });
                    }
                });

                setChatMessage(chatMessage);
            }

        }

        /// <summary>
        /// 设置聊天内容
        /// </summary>
        /// <param name="chatMessages"></param>
        public void setChatMessage(List<ChatMessage> chatMessages)
        {
            Dispatcher.BeginInvoke(new Action(delegate
            {
                ListChatContent.ItemsSource = chatMessages;

                idScrollViewerASC.ScrollToBottom();

                //设置数据到最底部
                idScrollViewerASC.ScrollToVerticalOffset(idScrollViewerASC.ActualHeight + idScrollViewerASC.ViewportHeight + idScrollViewerASC.ExtentHeight + idScrollViewerASC.VerticalOffset);

            }));
            
        }

        /// <summary>
        /// 更改按钮颜色
        /// </summary>
        /// <param name="sender"></param>
        public void ChangeButtonChecked(object sender)
        {
            Button? button = sender as Button;
            BrushConverter conv = new BrushConverter();
            Brush bru = conv.ConvertFromInvariantString("#bee6fd") as Brush;
            button.Background = (System.Windows.Media.Brush)bru;
        }

        /// <summary>
        /// 0预定客户点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Booking_Customers_Click(object sender, RoutedEventArgs e)
        {
            ChangeButtonChecked(sender);
            GetChatUser(0);
        }

        /// <summary>
        /// 1在住客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Resident_Customers_Click(object sender, RoutedEventArgs e)
        {
            ChangeButtonChecked(sender);
            GetChatUser(1);
        }

        /// <summary>
        /// 2离店客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Outbound_Customers_Click(object sender, RoutedEventArgs e)
        {
            ChangeButtonChecked(sender);
            GetChatUser(2);
        }

        /// <summary>
        /// 3意向客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Intended_Customers_Click(object sender, RoutedEventArgs e)
        {
            ChangeButtonChecked(sender);
            GetChatUser(3);
        }

        /// <summary>
        /// 4商城会员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mall_Members_Click(object sender, RoutedEventArgs e)
        {
            ChangeButtonChecked(sender);
            GetChatUser(4);
        }

        /// <summary>
        /// 5协议单位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Agreement_Unit_Click(object sender, RoutedEventArgs e)
        {
            ChangeButtonChecked(sender);
            GetChatUser(5);
        }

        /// <summary>
        /// 6门店职员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Store_Staff_Click(object sender, RoutedEventArgs e)
        {
            ChangeButtonChecked(sender);
            GetChatUser(6);
        }

        /// <summary>
        /// 7平台客服
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Customer_Service_Click(object sender, RoutedEventArgs e)
        {
            ChangeButtonChecked(sender);
            GetChatUser(7);
        }

        /// <summary>
        /// 消息发送按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Send_Msg_Click(object sender, RoutedEventArgs e)
        {
            SendMsg();
        }

        /// <summary>
        /// 消息发送方法
        /// </summary>
        private void SendMsg()
        {
            if (string.IsNullOrEmpty(login_token))
            {
                MessageBox.Show("请先登录后使用");
                return;
            }

            if (string.IsNullOrEmpty(msg_username) && string.IsNullOrEmpty(msg_group_code))
            {
                MessageBox.Show("聊天对象信息错误");
                return;
            }

            string sendMsg = textBox.Text.Trim();


            if (string.IsNullOrEmpty(sendMsg))
            {
                MessageBox.Show("还未输入内容");
                return;
            }

            if(mqttClient == null || !mqttClient.m_MqttClient.IsConnected)
            {
                MessageBox.Show("服务器异常,暂无法进行消息发送");
                return; 
            }

            //赋值到聊天框
            List<ChatMessage> chatMessages = new List<ChatMessage>();
            //type: 1  个人消息    "accessToken":"","userName":"","msg":"消息"
            if (!string.IsNullOrEmpty(msg_username) && string.IsNullOrEmpty(msg_group_code))
            {
                if (string.IsNullOrEmpty(login_username))
                {
                    Console.WriteLine("登录人信息错误");
                    return;
                }
                var postDataUser = new { type = 1, accessToken = login_token, sendUser = login_username, recipientUser = msg_username, userType = msg_user_type, msg = sendMsg, propertyId = login_hotel_id };
                //发送聊天数据
                SendChatMsg(JsonConvert.SerializeObject(postDataUser));
                //保存用户的聊天信息
                SqlLiteUtil.SaveChatContent(login_username, msg_username, sendMsg, DateUtil.NowDateZ());
                //获取聊天内容
                List<ChatContent> chatContents = SqlLiteUtil.QueryChatContent(login_username, msg_username);
                chatContents.ForEach(chatContent =>
                {
                    //获取发送者用户信息
                    ChatUser sendChatUser = SqlLiteUtil.QueryOneChatUser(msg_user_type, chatContent.sendUser);
                    if (null == sendChatUser)
                    {
                        Console.WriteLine("消息发送者不存在");
                        return;
                    }

                    if (chatContent.sendUser.Equals(login_username))
                    {
                        chatMessages.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = "0", MessageLocation = TypeLocalMessageLocation.chatSend, Avatar = login_avatar, NickName = login_nickname, CreateTime = chatContent.createTime });
                    }
                    else
                    {
                        chatMessages.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = "0", MessageLocation = TypeLocalMessageLocation.chatRecv, Avatar = sendChatUser.avatar, NickName = sendChatUser.nickName, CreateTime = chatContent.createTime });

                    }
                });
            }

            //type: 2  群发消息 {type:2,"accessToken":"","groupCode": "111aa222"，"sendUser":"11111"，"msg":"消息"}
            if (string.IsNullOrEmpty(msg_username) && !string.IsNullOrEmpty(msg_group_code))
            {
                string groupCreateTime = DateUtil.NowDateZ();
                //{ type: 2,"accessToken":"","groupCode": "111aa222"，"sendUser":"11111"，"msg":"消息"}
                var postDataUser = new { type = 2, accessToken = login_token, groupCode = msg_group_code, sendUser = login_username, msg = sendMsg, createTime = groupCreateTime, propertyId = login_hotel_id };
                //发送聊天数据
                SendChatMsg(JsonConvert.SerializeObject(postDataUser));

                //保存群聊消息
                SqlLiteUtil.SaveChatGroupContent(msg_group_code, login_username, login_nickname, login_avatar, sendMsg, groupCreateTime, "0");
                //获取聊天内容
                chatGroupContents.Add(new ChatGroupContent(msg_group_code, login_username, login_nickname, login_avatar, sendMsg, groupCreateTime, "0"));

                chatGroupContents = chatGroupContents.OrderBy(s => s.createTime).ToList();

                chatGroupContents.ForEach(chatContent =>
                {
                    if (chatContent.sendUser.Equals(login_username))
                    {
                        chatMessages.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = "0", MessageLocation = TypeLocalMessageLocation.chatSend, Avatar = login_avatar, NickName = chatContent.nickName, CreateTime = chatContent.createTime });
                    }
                    else
                    {
                        chatMessages.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = "0", MessageLocation = TypeLocalMessageLocation.chatRecv, Avatar = chatContent.avatar, NickName = chatContent.nickName, CreateTime = chatContent.createTime });
                    }
                });
            }

            setChatMessage(chatMessages);
            //清空聊天输入框
            textBox.Text = "";
        }

        /// <summary>
        /// 进入设置界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Into_Setting_Click(object sender, MouseButtonEventArgs e)
        {
            SettingWindow settingWindow =new SettingWindow();
            settingWindow.ShowDialog();
        }

        

        /// <summary>
        /// 获取无线网络信号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetWlanStatus()
        {
            var wlanStatus = "无网络";
            NetWorkLabel.Content = wlanStatus;
            Color color = (Color)ColorConverter.ConvertFromString("Red");
            NetWorkLabel.Foreground = new SolidColorBrush(color);
            try
            {
                WlanClient wlanClient = new WlanClient();

                foreach (WlanClient.WlanInterface wlanIface in wlanClient.Interfaces)
                {
                    if (wlanIface.InterfaceState == Wlan.WlanInterfaceState.Connected && wlanIface.CurrentConnection.isState == Wlan.WlanInterfaceState.Connected)
                    {
                        Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);
                        foreach (var network in networks)
                        {
                            if (network.profileName == wlanIface.CurrentConnection.profileName
                                && (int)network.flags == (int)(Wlan.WlanAvailableNetworkFlags.Connected | Wlan.WlanAvailableNetworkFlags.HasProfile))
                            {
                                switch (network.wlanSignalQuality / 25)
                                {
                                    case 0:
                                        wlanStatus = "信号强度很差";
                                        NetWorkLabel.Content = wlanStatus;
                                        Color color1 = (Color)ColorConverter.ConvertFromString("#bd444d");
                                        NetWorkLabel.Foreground = new SolidColorBrush(color1);
                                        break;
                                    case 1:
                                        wlanStatus = "信号强度差";
                                        NetWorkLabel.Content = wlanStatus;
                                        Color color2 = (Color)ColorConverter.ConvertFromString("#cfa74c");
                                        NetWorkLabel.Foreground = new SolidColorBrush(color2);
                                        break;
                                    case 2:
                                        wlanStatus = "信号强度较差";
                                        NetWorkLabel.Content = wlanStatus;
                                        Color color3 = (Color)ColorConverter.ConvertFromString("#cfa74c");
                                        NetWorkLabel.Foreground = new SolidColorBrush(color3);
                                        break;
                                    default:
                                        wlanStatus = "信号强度优";
                                        NetWorkLabel.Content = wlanStatus;
                                        Color color4 = (Color)ColorConverter.ConvertFromString("#6fe695");
                                        NetWorkLabel.Foreground = new SolidColorBrush(color4);
                                        break;
                                }
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            catch (Exception e)
            {

            }
        }

        private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            ScrollViewer scrollviewer = sender as ScrollViewer;
            if (e.Delta > 0)
                scrollviewer.LineUp();
            else
                scrollviewer.LineDown();
            e.Handled = true;
        }

        /// <summary>
        /// 获取群组编码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GetGroupCode(object sender, MouseButtonEventArgs e)
        {
            StackPanel? s = sender as StackPanel;
            if (s != null)
            {

                ChatGroupUserGrid.Visibility = Visibility.Hidden;

                ChatGroup _chatGroup = s.Tag as ChatGroup;
                msg_group_code = _chatGroup.groupCode;

                msg_username = "";
                msg_user_type = -1;
                if (string.IsNullOrEmpty(msg_group_code))
                {
                    MessageBox.Show("聊天对象信息错误");
                    return;
                }
                else
                {
                    //展示出聊天框
                    ChatGrid.Visibility = Visibility.Visible;
                    ShowGroupUser.Visibility = Visibility.Visible;
                    //如果群是异常状态  则禁用聊天输入框和发送按钮
                    if (_chatGroup.status.Equals("1"))
                    {
                        textBox.IsReadOnly = false;
                        SendMsgBtn.IsEnabled = false;
                    }
                    Chat_Object.Content = _chatGroup.groupName;
                }

                //获取与当前用户的最后一条记录信息
                string lastTime = SqlLiteUtil.QueryChatGroupContentByLastTime(login_username, msg_group_code);

                //获取离线聊天内容
                var postDataUser = new { type = 9, accessToken = login_token, startTime = lastTime, groupCode = msg_group_code, propertyId = login_hotel_id };
                //发送聊天数据
                SendChatMsg(JsonConvert.SerializeObject(postDataUser));

                //赋值到聊天框
                List<ChatMessage> chatMessages = new List<ChatMessage>();
                //获取群聊天信息并赋值
                chatGroupContents = SqlLiteUtil.QueryChatGroupContent(login_username, msg_group_code);
                chatGroupContents.ForEach(chatContent =>
                {
                    if (chatContent.sendUser.Equals(login_username))
                    {
                        chatMessages.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = chatContent.msgType, MessageLocation = TypeLocalMessageLocation.chatSend, Avatar = chatContent.avatar, NickName = chatContent.nickName, CreateTime = chatContent.createTime });
                    }
                    else
                    {
                        chatMessages.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = chatContent.msgType, MessageLocation = TypeLocalMessageLocation.chatRecv, Avatar = chatContent.avatar, NickName = chatContent.nickName, CreateTime = chatContent.createTime });
                    }
                });

                setChatMessage(chatMessages);
                idScrollViewerASC.ScrollToBottom();


            }
        }

        /// <summary>
        /// 个人列表与群组列表切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabControlUser_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string tabItem = ((sender as TabControl).SelectedItem as TabItem).Header as string;
            if ("群聊".Equals(tabItem))
            {
                if (mqttClient != null && mqttClient.m_MqttClient!=null && mqttClient.m_MqttClient.IsConnected)
                {
                    GetChatGroup();
                }

            }
            if ("联系人".Equals(tabItem))
            {
                if (mqttClient != null &&  mqttClient.m_MqttClient !=null && mqttClient.m_MqttClient.IsConnected)
                {
                    GetChatUser(0);
                }

            }

        }

        /// <summary>
        /// 快速发送消息 ENTER
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void quickly_send_msg(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                try
                {
                    SendMsg();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "Error");
                }

            }
            
        }

        /// <summary>
        /// 查看群成员
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowUserItem(object sender, MouseButtonEventArgs e)
        {
            var postDataUser = new { type = 6, accessToken = login_token, groupCode=msg_group_code, propertyId = login_hotel_id};
            SendChatMsg(JsonConvert.SerializeObject(postDataUser));

            //查询用户列表
            List<GroupUserItem> userItems =  SqlLiteUtil.QueryGroupUser(msg_group_code);
            if(null != userItems)
            {

                ChatGrid.Visibility = Visibility.Hidden;
                ChatGroupUserGrid.Visibility = Visibility.Visible;

                Dispatcher.BeginInvoke(new Action(delegate
                {
                    ChatGroupUserListView.ItemsSource = userItems;
                }));
            }

        }


        /// <summary>
        /// T³点击页面跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void JumpToPage(object sender, MouseButtonEventArgs e)
        {
            //跳转到T3PMS
            string t3pmsUrl = AppConfigUtil.GetValue("ExternalLinks", "T3PMS");
            if(!string.IsNullOrEmpty(t3pmsUrl))
            {
                System.Diagnostics.Process.Start("explorer.exe", t3pmsUrl);
            }
        }

        /// <summary>
        /// 选择图片发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ChooseImg(object sender, MouseButtonEventArgs e)
        {
            OpenFileDialog openfiledialog = new OpenFileDialog();
            openfiledialog.Filter = "图片|*.gif;*.jpg;*.jpeg;*.bmp;*.jfif;*.png;";

            if ((bool)openfiledialog.ShowDialog())
            {
                string base64img = ImgUtil.GetUrlToBase64(openfiledialog.FileName);
                //Image1.Source = new BitmapImage();

                //发送数据
                string groupCreateTime = DateUtil.NowDateZ();
                //{ type: 2,"accessToken":"","groupCode": "111aa222"，"sendUser":"11111"，"msg":"消息"}
                var postDataUser = new { type = 2, accessToken = login_token, groupCode = msg_group_code, sendUser = login_username, msgType = "1", msg = base64img, createTime = groupCreateTime, propertyId = login_hotel_id };
                //发送聊天数据
                SendChatMsg(JsonConvert.SerializeObject(postDataUser));

                //保存群聊消息
                SqlLiteUtil.SaveChatGroupContent(msg_group_code, login_username, login_nickname, login_avatar, base64img, groupCreateTime, "1");

                //追加聊天内容
                chatGroupContents.Add(new ChatGroupContent(msg_group_code, login_username, login_nickname, login_avatar, base64img, groupCreateTime, "1"));

                chatGroupContents = chatGroupContents.OrderBy(s => s.createTime).ToList();

                //赋值到聊天框
                List<ChatMessage> chatContents = new List<ChatMessage>();

                chatGroupContents.ForEach(chatContent =>
                {
                    if (chatContent.sendUser.Equals(login_username))
                    {
                        chatContents.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = chatContent.msgType, MessageLocation = TypeLocalMessageLocation.chatSend, Avatar = chatContent.avatar, NickName = chatContent.nickName, CreateTime = chatContent.createTime });
                    }
                    else
                    {
                        chatContents.Add(new ChatMessage() { Message = chatContent.chatMsg, MsgType = chatContent.msgType, MessageLocation = TypeLocalMessageLocation.chatRecv, Avatar = chatContent.avatar, NickName = chatContent.nickName, CreateTime = chatContent.createTime });
                    }

                });
                setChatMessage(chatContents);
                //setChatMessage(chatMessages);
            }
        }

        /// <summary>
        /// 显示聊天界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowGroupMsg(object sender, MouseButtonEventArgs e)
        {
            ChatGroupUserGrid.Visibility = Visibility.Hidden;
            //展示出聊天框
            ChatGrid.Visibility = Visibility.Visible;
            ShowGroupUser.Visibility = Visibility.Visible;

        }

        /// <summary>
        /// 鼠标左键跳转到链接地址
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListChatContent_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            ChatMessage chatMessage = (ChatMessage)((ListBox)sender).SelectedItem;
            string msgStr = chatMessage.Message.ToString();

            if (StrUtils.IsURL(msgStr))
            {
                System.Diagnostics.Process.Start("explorer.exe", msgStr);
            }
            else
            {
                string urlStr =StrUtils.GetURL(msgStr);
                if (StrUtils.IsURL(urlStr))
                {
                    System.Diagnostics.Process.Start("explorer.exe", urlStr);
                }
            }

        }

        /// <summary>
        /// 鼠标右键文本信息复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListChatContent_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            ChatMessage chatMessage = (ChatMessage)((ListBox)sender).SelectedItem;
            string msgStr = chatMessage.Message.ToString();
            Clipboard.SetText(msgStr);
            MessageBox.Show("数据复制成功");
        }

        /// <summary>
        /// 智能发卡器点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            OfflineCard offlineCard = new OfflineCard();
            /*Window window = Window.GetWindow(this);//关闭父窗体
            window.Close();*/
            offlineCard.Show();
            /*OfflineCard offlineCard = new OfflineCard();
            string plaintext = "20 00 00 00 00 00 00 00 00 7A 68 61 6E 67 73 61 6E 30 31".Trim();
            string keyString = "79 67 6c 6f 63 6b 2e 63 6f 6d".Trim();
            offlineCard.aa(keyString,plaintext);*/
        }

    }
}